import json
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from students.models import Class
from .models import AdminUser, Department, Role
from .serializers import AdminUserSerializers, DepartmentSerializers, RoleSerializers, UserRoleSerializers


class AdminUserView(ModelViewSet):
    queryset = AdminUser.objects.all()
    serializer_class = AdminUserSerializers
    def update(self, request, *args, **kwargs):
        #实现局部更新
        return super().update(request,partial=True)
    #获取学院所有老师
    def getCollegeTeachers(self,request):
        cls_id = request.query_params.get('class_id')
        try:
            # 根据班级id 获取对应的学院
            cls = Class.objects.get(pk=cls_id)
            # 根据学院获取 所有的老师角色
            roles = cls.school.role_set.filter(level=3)
            # 获取所有拥有老师角色的员工
            adminuser=AdminUser.objects.filter(role__in=roles).values('id','name','role__duty')
        except:
            adminuser = []
        return Response(adminuser)
        #self.pagination_class = None # 控制分页

class RoleView(ModelViewSet):

    def get_queryset(self):
        id = self.request.query_params.get('id')
        if id:
            return Role.objects.filter(department_id=id)
        return super().get_queryset()
    queryset = Role.objects.all()
    serializer_class = RoleSerializers
    @action(methods=['get'],detail=False)
    def filter_roles(self,request):
        department_ids=request.query_params.get('ids') #获取的部门的id [1,2,3]
        if department_ids:
            queryset = Role.objects.filter(department_id__in=json.loads(department_ids))
        role_ids = request.query_params.get('role_ids') #获取的角色id列表 [1,2,3]
        if role_ids:
            queryset = Role.objects.filter(id__in=json.loads(role_ids))
        ser=self.get_serializer(queryset,many=True)
        return Response(ser.data)

    @action(methods=['get'], detail=False)
    def getUserRole(self,request):
        if request.user.is_superuser:
            return Response({'is_superuser':1})
        roles = request.user.role.all()  # 获取用户的角色信息
        ser = UserRoleSerializers(roles, many=True)
        return Response(ser.data)








